import os
from meta_service.ucentre import AnyLancer
from .config import PDF_DUMP_DIR
from meta_service.utils import get_file_size
from .config import TIS_HANDLE
from meta_service.tistore import MAIN_TIS

MAIN_TIS.EnsureTopicHandle(TIS_HANDLE)

def GetPDFPath(entry_id:str,save_dir:str=None):
    filename = f"{entry_id}.pdf"
    if save_dir is None:
        handle = MAIN_TIS.GetTopicHandle(TIS_HANDLE)
        if handle is None:
            raise Exception(f"cannot get topic handle: {TIS_HANDLE}")
        if handle.HasIndex(filename):
            index_handle = handle.GetIndexHandle(filename)
            return index_handle.GetIndexPath()
        return None
    # 自定义路径
    file_path = os.path.join(save_dir,filename)
    if os.path.exists(file_path) and os.path.isfile(file_path):
        return file_path
    return None

def IsPdfExist(entry_id:str,save_dir:str=None):
    filename = f"{entry_id}.pdf"
    if save_dir is None:
        handle = MAIN_TIS.GetTopicHandle(TIS_HANDLE)
        if handle is None:
            raise Exception(f"cannot get topic handle: {TIS_HANDLE}")
        return handle.HasIndex(filename)
    # 自定义路径
    file_path = os.path.join(save_dir,filename)
    return os.path.exists(file_path) and os.path.isfile(file_path)

def TryDownloadPDF(entry_id:str,save_dir:str=None):
    """
    尝试下载文件,如果下载失败则返回False
    """
    if IsPdfExist(entry_id,save_dir):
        return True
    file_name = f"{entry_id}.pdf"
    try:
        paper = AnyLancer(entry_id)
        if save_dir is None:
            # 创建保存文件的Handle
            handle = MAIN_TIS.GetTopicHandle(TIS_HANDLE)
            if handle is None:
                raise Exception(f"cannot get topic handle: {TIS_HANDLE}")
            # 获取文件
            index_handle = handle.NewTempIndex(file_name)
            index_file_path = index_handle.GetIndexPath()
            paper.download_to_file(index_file_path)
            # 检查文件大小
            if get_file_size(index_file_path) > 0:
                index_handle.TurnOn()
                return True
            return False
        # 自定义路径
        paper.download_to_dir(save_dir)
        file_path = os.path.join(save_dir,file_name)
        if get_file_size(file_path) > 0:
            return True
        return False
    except Exception as e:
        print(f"try download pdf for {entry_id} but failed: {str(e)}")
        return False
